using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Managers.ResourceManagement;

namespace Yoozoo.Modules.TraceEvent
{
    public class ApmReportManager : MonoBehaviour
    {
        
        public static ApmReportManager Instance;
        private int _selfAddId = 0;
        private int _currentId = -1;
        private Dictionary<int, ApmReport> reportDictionary = new Dictionary<int, ApmReport>(4);
        private string performanceSvrPath;
        
        //客户端ClientApm发送的服务器API地址
        private string _clientApmUrl = string.Format("{0}api?action=clientApm", AppConfig.ServerApiPath);

        private void Awake()
        {
            Instance = this;
        }

        public void InitUrl(string url)
        {
            performanceSvrPath = url;
        }

        /// <summary>
        /// 启动APM采集
        /// </summary>
        /// <param name="isSelfDestory">是否自动销毁</param>
        /// <param name="sampleTimeInterval">自动采集间隔</param>
        /// <param name="minTimeInterval">自动采集最小间隔</param>
        /// <param name="sceneName">采集场景</param>
        /// <param name="sceneArg">采集场景参数</param>
        /// <param name="loadingTime">加载时长</param>
        /// <returns></returns>
        public int StartCollect(bool isSelfDestory, float sampleTimeInterval = 0, float minTimeInterval = 0,
            string sceneName = "", string sceneArg = "", string loadingTime = "")
        {
            int id = _selfAddId++;
#if EventTrace
            Debug.Log("StartCollect:" + id);
            GameObject reportObj = new GameObject($"ApmReport_{id}");
            var reportMono = reportObj.AddComponent<ApmReport>();
            reportMono.InitParam(
                _clientApmUrl, 
                sampleTimeInterval, 
                minTimeInterval,
                isSelfDestory, 
                sceneName, 
                sceneArg,
                loadingTime);
            if (!isSelfDestory)
            {
                reportDictionary.Add(id, reportMono);
            }

            _currentId = id;
#endif
            return id;
        }

        /// <summary>
        /// 停止APM采集，并主动上报数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isInterval">是否定时发送</param>
        public void StopCollectAndSendReport(int id, bool isInterval = false)
        {
#if EventTrace
            Debug.Log("StopCollectAndReport:" + id);
            if (reportDictionary.TryGetValue(id, out var report))
            {
                report.StopCollectAndSendReport(isInterval);
                reportDictionary.Remove(id);
            }
#endif
        }

        /// <summary>
        /// 停止APM采集，但不上报数据
        /// </summary>
        /// <param name="id"></param>
        public void StopCollect(int id)
        {
#if EventTrace
            Debug.Log("StopCollect:" + id);
            if (reportDictionary.TryGetValue(id, out var report))
            {
                report.StopCollect();
                reportDictionary.Remove(id);
            }
#endif
        }

        /// <summary>
        /// 停止所有APM采集，并上报所有数据
        /// </summary>
        public void StopCollectAndSendAllData()
        {
#if EventTrace
            Debug.Log("StopCollectAndSendAllData");
            if (reportDictionary != null)
            {
                var enumerator = reportDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var point = enumerator.Current.Value;
                    point.StopCollectAndSendReport();
                }

                enumerator.Dispose();
                reportDictionary.Clear();
            }
#endif
        }

        /// <summary>
        /// 停止所有APM采集，且不上报数据
        /// </summary>
        public void StopCollectAll()
        {
#if EventTrace
            Debug.Log("StopCollectAll");
            if (reportDictionary != null)
            {
                var enumerator = reportDictionary.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var point = enumerator.Current.Value;
                    point.StopCollect();
                }

                enumerator.Dispose();
                reportDictionary.Clear();
            }
#endif
        }

        /// <summary>
        /// 获取帧率超过18的比率
        /// </summary>
        /// <returns></returns>
        public float GetOverFrame18Percent()
        {
            float percent = 0;
#if EventTrace
            Debug.Log("GetOverFrame18Percent:" + _currentId);
            ApmReport report;
            reportDictionary.TryGetValue(_currentId, out report);
            if (report != null)
                percent = report.GetOverFrame18Percent();
#endif
            return percent;
        }

        /// <summary>
        /// 获取平均帧率值
        /// </summary>
        /// <returns></returns>
        public float GetAverageFps()
        {
            float avg = 0;
#if EventTrace
            Debug.Log("GetAverageFps:" + _currentId);
            ApmReport report;
            reportDictionary.TryGetValue(_currentId, out report);
            if (report != null)
                avg = report.GetAverageFps();
#endif
            return avg;
        }
    }
}